<template>
  <div class="news-list">
    <div class="list-serach">
      <a-input-search
        size="default"
        v-model="searchId"
        placeholder="请输入新闻id"
        enter-button
        @search="searchById"
      />
      <a-button type="primary" @click="resetSearch">重置搜索条件</a-button>
    </div>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="newsList"
      :pagination="false"
      :rowKey="(record) => record.id"
    >
      <span slot="customTitle">新闻id</span>
      <span slot="pic" slot-scope="text, record">
        <img
          style="
            width: 100px;
            height: 100px;
            border-radius: 5%;
            box-shadow: 2px 2px 5px #333333;
          "
          :src="record.cover"
        />
      </span>
      <span slot="projectName" v-if="projectName">
        <span>{{ projectName }}</span>
      </span>
      <span slot="action" slot-scope="text, record">
        <a-button
          type="primary"
          style="margin-right: 8px"
          icon="eye"
          @click="showDetail(record.id)"
          >查看</a-button
        >
        <a-button
          type="danger"
          style="margin-right: 8px"
          icon="delete"
          @click="delSingle(record.id)"
          >删除</a-button
        >
      </span>
    </a-table>
    <div class="bottom">
      <div class="button-group">
        <a-button type="primary" icon="plus" class="add" @click="addNews">
          新增
        </a-button>
        <a-button type="danger" class="del-list-btn" @click="delAll"
          >删除选中</a-button
        >
      </div>

      <a-pagination
        class="pageTab"
        show-quick-jumper
        :current="current"
        :page-size-options="pageSizeOptions"
        :total="newsNum"
        :show-total="(total) => `共 ${newsNum} 条`"
        :page-size="limit"
        :default-current="1"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />
      <a-modal
        centered
        title="删除新闻"
        v-model="delModalVisible"
        @ok="delOk"
        @cancel="delNo"
      >
        <p>此操作不可逆！确认删除？</p>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {
  delNewsApi,
  getNewsListApi,
  getNewsByIdApi,
} from '@/services/webApi/news';
import moment from 'moment';
export default {
  data() {
    return {
      columns: [
        {
          title: '新闻id',
          dataIndex: 'id',
          key: 'newsId',
          align: 'center',
        },
        {
          title: '新闻标题',
          dataIndex: 'title',
          key: 'title',
          align: 'center',
        },
        {
          title: '封面图片',
          dataIndex: 'cover',
          key: 'cover',
          scopedSlots: { customRender: 'pic' },
          align: 'center',
        },
        {
          title: '项目id',
          dataIndex: 'projectId',
          key: 'projectId',
          align: 'center',
        },
        {
          title: '项目名称',
          scopedSlots: { customRender: 'projectName' },
          key: 'projectName',
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
          align: 'center',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      searchId: '',
      newsNum: 0, //新闻数量
      pageSizeOptions: ['5', '10', '15', '20', '25'], //每页新闻数选择
      current: 1, //当前页面
      limit: 5, //每页多少条
      newsList: [],
      selectedRowKeys: [], //选择的列数
      currentNewsId: 0,
      delModalVisible: false,
      action: '', // 删除单条还是多条
      projectName: '',
    };
  },
  async created() {
    this.getNewsList(this.limit, 0);
  },
  methods: {
    // 新增新闻
    addNews() {
      this.$router.push(`newsDetail/0`);
    },
    // 重置搜索
    async resetSearch() {
      this.searchId = '';
      this.$message.success(`重置搜索条件成功`, 1.5);
      this.getNewsList(this.limit, 0);
      this.current = 1;
      this.newsList = [];
    },
    // 按id搜索
    searchById() {
      if (!this.searchId) {
        return;
      }
      this.getNewsById();
    },
    // 按id获取单个
    async getNewsById() {
      try {
        let res = await getNewsByIdApi({
          id: this.searchId - 0,
        });
        this.newsList = res.data ? [res.data] : [];
        if (this.newsList) {
          this.newsList[0].createdAt = moment(
            this.newsList[0].createdAt
          ).format('YYYY-MM-DD  HH:mm:ss');
        }
        this.newsNum = this.newsList.length;
      } catch (error) {
        this.searchId = '';
        this.$message.error(`请重新输入`, 1);
        setTimeout(() => {
          this.getNewsList(this.limit, 0);
          this.current = 1;
        }, 1000);
      }
    },
    // 获取新闻列表
    async getNewsList(limit, offset) {
      let res = await getNewsListApi({
        limit,
        offset,
      });
      this.newsList = res.data.rows;
      this.newsList.forEach((ele) => {
        ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
      });
      this.newsNum = res.data.count;
      this.projectName = res.data.projectName;
    },
    // 跳转新闻详情
    showDetail(id) {
      this.$router.push(`/web/news/newsDetail/${id}`);
    },
    // 删除单条modal框
    delSingle(id) {
      this.currentNewsId = id;
      this.delModalVisible = true;
      this.action = 'deleteSingle';
    },
    // 删除多条modal框
    delAll() {
      this.action = 'deleteAll';
      let flag = this.selectedRowKeys.length;
      if (flag == 0) {
        this.$message.error('未选中任何新闻', 1);
      } else {
        this.delModalVisible = true;
      }
    },
    // 确认删除
    async delOk() {
      switch (this.action) {
        case 'deleteSingle': {
          let res = await this.delNews();
          res.code == 200 && this.$message.success(res.msg, 1);
          this.delModalVisible = false;
          break;
        }
        case 'deleteAll':
          this.delAllNews();
          break;
      }
      this.searchId = '';
      // 请求新数据
      this.getNewsList(this.limit, 0);
      this.current = 1;
    },
    //删除操作
    async delNews(id = this.currentNewsId) {
      this.currentNewsId = '';
      return await delNewsApi({
        id,
      });
    },
    // 删除多条的操作
    delAllNews() {
      let delArr = this.selectedRowKeys;
      try {
        delArr.map((ele) => {
          this.delNews(ele);
        });
      } catch (error) {
        this.$message.error('删除失败', 1);
      }
      this.$message.success(`成功删除${delArr.length}条新闻`, 1);
      this.selectedRowKeys = [];
      this.delModalVisible = false;
    },
    // 取消删除
    delNo() {
      this.delModalVisible = false;
      this.$message.info('取消删除', 1);
    },
    // 多选
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      this.limit = pageSize;
      this.pageChange(current);
    },
    pageChange(current) {
      this.current = current;
      let offset = (this.current - 1) * this.limit;
      this.getNewsList(this.limit, offset);
    },
  },
};
</script>

<style lang="scss" scoped>
.add {
  margin-bottom: 10px;
}
.list-serach {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1rem;
  .ant-input-search {
    width: 200px;
  }
  .admin-search {
    .ant-select {
      min-width: 80px;
      .ant-select-selection {
        display: flex;
        flex-direction: column;
      }
    }
  }
  .ant-input-group {
    display: flex;
  }
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  .button-group {
    button {
      margin-right: 10px;
    }
  }
  .pageTab {
    text-align: right;
  }
  .del-list-btn {
    text-align: center;
  }
}
</style>
